<?php

namespace addons\helper\library;

use fast\Http;

class Weapp
{
    /**
     * code换取session_key
     *
     * @param string $AppID
     * @param string $AppSecret
     * @param string $code
     * @return json
     */
    public static function code2Session($AppID, $AppSecret, $code)
    {
        $params = [
            'appid'      => $AppID,
            'secret'     => $AppSecret,
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];
        $result = Http::get("https://api.weixin.qq.com/sns/jscode2session", $params);
        $result = json_decode($result, true);
        return $result;
    }

    /**
	 * 检验数据的真实性，并且获取解密后的明文.
     * 
     * @param string $appId             小程序ID
	 * @param string $encryptedData     待解密的用户数据
	 * @param string $iv                与用户数据一同返回的初始向量
	 * @param string $sessionKey        code换取的session_key
	 * @return array $data              解密后的原文 code: 成功0，失败返回对应的错误码
	 */
	public static function decryptData($appId, $encryptedData, $iv, $sessionKey)
	{
		if (strlen($sessionKey) != 24) {
			$data = [
				'code' => -41001,
				'msg'  => 'encodingAesKey非法',
				'data' => []
			];
			return $data;
		}
		$aesKey = base64_decode($sessionKey);

		if (strlen($iv) != 24) {
			$data = [
				'code' => -41002,
				'msg'  => 'iv非法',
				'data' => []
			];
			return $data;
		}
		$aesIV     = base64_decode($iv);
		$aesCipher = base64_decode($encryptedData);
		$result    = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
		$dataObj   = json_decode($result);
		if ($dataObj  == NULL) {
			$data = [
				'code' => -41002,
				'msg'  => '解密后得到的buffer非法',
				'data' => []
			];
			return $data;
		}
		if ($dataObj->watermark->appid != $appId) {
			$data = [
				'code' => -41003,
				'msg'  => '水印效验失败',
				'data' => []
			];
			return $data;
		}
		$data = [
			'code' => 0,
			'msg'  => '解密成功',
			'data' => json_decode($result, true)
		];
		return $data;
	}
}
